package com.bzyd.ss.handler;

import lombok.Data;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义登录成功后的处理器
 * 转发或重定向，由代码决定
 */
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    private String url;
    private boolean isRedirect;

    public MyAuthenticationSuccessHandler(String url, boolean isRedirect) {
        this.url = url;
        this.isRedirect = isRedirect;
    }

    /**
     * @param request 请求对象，request.getRequestDispatcher().forward() -- 请求转发
     * @param response 响应对象，response.sendRedirect() -- 响应重定向
     * @param authentication 用户认证（登录）成功后的对象，其中包含用户名和权限集合，内容是
     *                       自定义的UserDetailsService实现的方法返回值对象提供的，如：org.springframework.security.core.userdetails.User
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
        System.out.println("自定义登录成功处理逻辑执行。。。");
        System.out.println("ServletPath：" + request.getServletPath());
        System.out.println("用户凭证：" + authentication.getCredentials());
        System.out.println("用户身份：" + authentication.getPrincipal());
        System.out.println("用户名称：" + authentication.getName());
        System.out.println("用户明细：" + authentication.getDetails());
        System.out.println("用户权限：" + authentication.getAuthorities());
        if (isRedirect){
            response.sendRedirect(url);
        }else {
            request.getRequestDispatcher(url).forward(request,response);
        }
    }
}
